package sse.ustc.cc.fragment;

import java.util.ArrayList;

import sse.ustc.cc.activity.R;
import sse.ustc.cc.util.AroundSchool;
import sse.ustc.cc.util.SchoolInfoParser;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

/**
 * 导入课程fragment
 * 
 * @author xuhao
 * 
 */
public class LeadCourseFrag extends Fragment {

	private static String[] schoolInfo;
	private Spinner spinner;
	private static ArrayAdapter<String> adapter;
	private ProgressDialog pd;

	private ArrayList<AroundSchool> aroundSchoolList = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		pd = new ProgressDialog(getActivity());
		pd.setMessage("正在定位您周围的学校，请稍后...");
		pd.setCanceledOnTouchOutside(false);
		pd.show();
		
		initdata();
		View rootView = inflater.inflate(R.layout.leadcourse, container, false);// 关联布局文件

		spinner = (Spinner) rootView.findViewById(R.id.Spinner01);

		return rootView;
	}

	private void initdata() {
		// 在ui主线程中调用gps，http服务
		 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		 .detectDiskReads().detectDiskWrites().detectNetwork()
		 .penaltyLog().build());
		 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		 .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
		 .penaltyLog().penaltyDeath().build());
		 
		 GPSInfoProvider2 location = new GPSInfoProvider2();
		 location.getLocation();
		 

	}

	public void initView() {
		pd.dismiss();
		if(aroundSchoolList == null){
			Log.i("aroundSchoolList>>>>", "aroundSchoolList为空");
		}else{
			Log.i("aroundSchoolList>>>>", aroundSchoolList.size() + "");
			schoolInfo = new String[aroundSchoolList.size()];
			for (int i = 0; i < aroundSchoolList.size(); i++) {
				Log.i("schoolInfo", aroundSchoolList.get(i).getSchoolName());
				schoolInfo[i] = aroundSchoolList.get(i).getSchoolName();

			}
		}
		
		 adapter = new ArrayAdapter<String>(getActivity(),
		 android.R.layout.simple_spinner_item, schoolInfo);
		 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		 // 将adapter 添加到spinner中
		 spinner.setAdapter(adapter);
		 // 添加事件Spinner事件监听
		 spinner.setOnItemSelectedListener(new SpinnerSelectedListener());
		 // 设置默认值
		 spinner.setVisibility(View.VISIBLE);
	}

	// 使用数组形式操作
	class SpinnerSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}
	
	/**
	 * 1、gps  获取经纬度
	 * 2、获得该经纬度周围的学校
	 * @author xuhao
	 *
	 */
	class GPSInfoProvider2 {
		private LocationManager manager;
		private MyLoactionListener listener;
		private Location mylocation;
		
		private double lat = 0.0;
		private double lng = 0.0;
		
		// 获取gps 信息
		public void getLocation() {
			manager = (LocationManager) getActivity()
					.getSystemService(Context.LOCATION_SERVICE);
			// manager.getAllProviders(); // gps //wifi //
			String provider = getProvider(manager);
			// 注册位置的监听器
			manager.requestLocationUpdates(provider, 60000, 50, getListener());

		}

		private synchronized MyLoactionListener getListener() {
			if (listener == null) {
				listener = new MyLoactionListener();
			}
			return listener;
		}

		private class MyLoactionListener implements LocationListener {

			/**
			 * 当手机位置发生改变的时候 调用的方法
			 */
			public void onLocationChanged(Location location) {
				if (location != null) {
					mylocation = location;
					updateMyLocation();
				} else {
					Log.i("onLocationChanged", "位置不可得");
				}

			}

			/**
			 * 某一个设备的状态发生改变的时候 调用 可用->不可用 不可用->可用
			 */
			public void onStatusChanged(String provider, int status, Bundle extras) {

			}

			/**
			 * 某个设备被打开
			 */
			public void onProviderEnabled(String provider) {

			}

			/**
			 * 某个设备被禁用
			 * 
			 */
			public void onProviderDisabled(String provider) {

			}

		}

		private void updateMyLocation() {
			stopGPSListener();
			lat = mylocation.getLatitude(); // weidu
			lng = mylocation.getLongitude(); // jingdu
			aroundSchoolList = SchoolInfoParser.getUpdataInfo(lat, lng);
			initView();
		}

		// 停止gps监听
		public void stopGPSListener() {
			manager.removeUpdates(getListener());
		}

		/**
		 * 
		 * @param manager
		 *            位置管理服务
		 * @return 最好的位置提供者
		 */
		private String getProvider(LocationManager manager) {
			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
			criteria.setSpeedRequired(true);
			criteria.setCostAllowed(true);
			return manager.getBestProvider(criteria, true);
		}

	}
	
	
}
